package com.hele.sts.pub;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import javax.media.jai.PlanarImage;

import org.apache.commons.io.IOUtils;

import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.TIFFEncodeParam;

public class TiffUtils {

	public static void deleteTifPage(String srcFile, String destFile, Integer[] ymArray) throws IOException {
		String tempDirectory = "c:\\ipm\\";
		int pageToBeDeleted = 1;
		List<RenderedImage> images = new ArrayList<RenderedImage>();
		FileSeekableStream ss = new FileSeekableStream(srcFile);
		ImageDecoder dec = ImageCodec.createImageDecoder("tiff", ss, null);
		int count = dec.getNumPages();
		// System.out.println(count);
		for (int i = 1; i <= count; i++) {
			if(Arrays.binarySearch(ymArray, i)>=0)
			//if (i == pageToBeDeleted)
				continue;
			PlanarImage op = new NullOpImage(dec.decodeAsRenderedImage(i - 1), null, null, OpImage.OP_IO_BOUND);
			images.add(op.getAsBufferedImage());
		}

		TIFFEncodeParam params = new TIFFEncodeParam();
		OutputStream out = new FileOutputStream(destFile);
		ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
		List imageList = new ArrayList();
		for (int i = 1; i < images.size(); i++) {
			imageList.add((BufferedImage) images.get(i));
		}
		params.setExtraImages(imageList.iterator());
		params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
		encoder.encode(images.get(0));
		out.close();
	}
	
	public static void main(String[] args) throws IOException {
		Integer[] a = {2};
		TiffUtils.deleteTifPage("d:\\2013-1018008\\test2.tif", "d:\\2013-1018008\\new.tif", a);
	}
	
	 public static boolean isValidTif(String tifFile){

	        FileSeekableStream ss = null;
	        try {
	            ss = new FileSeekableStream(tifFile);
	            ImageDecoder dec = ImageCodec.createImageDecoder("tiff", ss, null);
	            int count = dec.getNumPages();
	            //logger.debug("file: {},pageNum:{}",tifFile,count);
	            for (int i = 1; i <= count; i++) {

	                PlanarImage op = new NullOpImage(dec.decodeAsRenderedImage(i - 1), null, null, OpImage.OP_IO_BOUND);
	                //images.add(op.getAsBufferedImage());
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	          //  logger.debug("file:{} exception,{}",tifFile,e.getMessage());
	            return false;
	        } finally {
	            IOUtils.closeQuietly(ss);
	        }
	        return true;
	    }
}
